﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using System.Windows.Browser;
using CNVP_SilverlightClass.getInfo;
using System.Windows.Media.Imaging;
using System.Windows.Printing;

namespace CNVP_SilverlightClass
{
    public partial class MainPage : UserControl
    {
        Drag drag = new Drag();
        GetCommonSoapClient get = new GetCommonSoapClient();
        int DeliveryWay = 0;
        int OrderID = 0;
        int PostAddressID = 0;
        public MainPage()
        {
            if (HtmlPage.Document.QueryString["ID"] != "" && HtmlPage.Document.QueryString["ID"] != null)
            {
                DeliveryWay = int.Parse(HtmlPage.Document.QueryString["ID"]);
            }
            if (HtmlPage.Document.QueryString["OrderID"] != "" && HtmlPage.Document.QueryString["OrderID"] != null)
            {
                OrderID = int.Parse(HtmlPage.Document.QueryString["OrderID"]);
            }
            if (HtmlPage.Document.QueryString["PostAddressID"] != "" && HtmlPage.Document.QueryString["PostAddressID"] != null)
            {
                PostAddressID = int.Parse(HtmlPage.Document.QueryString["PostAddressID"]);
            }
            InitializeComponent();
            get.GetColumnByIDAsync(DeliveryWay);
            get.GetColumnByIDCompleted += new EventHandler<GetColumnByIDCompletedEventArgs>(GetColumnByIDCompleted);
            //获取位置列表
            get.GetAll_DeliveryTemplateAsync("DeliveryTemplateClassID=" + DeliveryWay);
            if (OrderID > 0)
            {
                
                    stackPanelTop.Visibility = Visibility.Collapsed;//不显示
                    get.GetAll_DeliveryTemplateCompleted += new EventHandler<GetAll_DeliveryTemplateCompletedEventArgs>(NoMove_GetAll_DeliveryTemplateCompleted);
                    // 收货人信息,订单信息等
                    get.GetDeliveryInfoByIdAsync(OrderID);
                    get.GetDeliveryInfoByIdCompleted += new EventHandler<GetDeliveryInfoByIdCompletedEventArgs>(GetDeliveryInfoByIdCompleted);
                   
            }
            else
            {
                get.GetAll_DeliveryTemplateCompleted += new EventHandler<GetAll_DeliveryTemplateCompletedEventArgs>(GetAll_DeliveryTemplateCompleted);
                stackPanelButton.Visibility = Visibility.Collapsed;//不显示
            }

        }

        /// <summary>
        /// 无法拖动矩形
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NoMove_GetAll_DeliveryTemplateCompleted(object sender, GetAll_DeliveryTemplateCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                foreach (CNVP_DeliveryTemplate temp in e.Result)
                {
                    drag.MainMap = MainMap;
                    drag.TextBlockName = temp.ItemName;
                    drag.NoMove_CreateRecForCan(true, true, temp.RectangleName, double.Parse(temp.MarginLeft.ToString()), double.Parse(temp.MarginTop.ToString()), double.Parse(temp.RectangleWidth.ToString()), double.Parse(temp.RectangleHight.ToString()), temp.ItemName);
                }
            }
        }
        /// <summary>
        /// 收货人信息,订单信息等
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetDeliveryInfoByIdCompleted(object sender, GetDeliveryInfoByIdCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                CNVP_Order singleOrder = e.Result;
                TextBlock itemText = null;
                UIElementCollection uiec = MainMap.Children;
                if (uiec.Count > 0)
                {
                    foreach (UIElement ui in uiec)
                    {
                        if (ui.GetType().ToString() == "System.Windows.Controls.TextBlock")
                        {
                            itemText = (TextBlock)ui;
                            #region 收货人信息,订单信息等
                            if (itemText.Text == "收货人-姓名")
                            {
                                itemText.Text = singleOrder.GetTrueName;
                            }
                            if (itemText.Text == "收货人-地区1级")
                            {
                                itemText.Text = singleOrder.Province;
                            }
                            if (itemText.Text == "收货人-地区2级")
                            {
                                itemText.Text = singleOrder.City;
                            }
                            if (itemText.Text == "收货人-地区3级")
                            {
                                itemText.Text = singleOrder.Area;
                            }
                            if (itemText.Text == "收货人-地址")
                            {
                                itemText.Text = singleOrder.GetAddress;
                            }
                            if (itemText.Text == "收货人-地区+详细地址")
                            {
                                itemText.Text = singleOrder.Province + singleOrder.City + singleOrder.Area + singleOrder.GetAddress;
                            }
                            if (itemText.Text == "收货人-电话")
                            {
                                itemText.Text = singleOrder.Phone;
                            }
                            if (itemText.Text == "收货人-手机")
                            {
                                itemText.Text = singleOrder.MobilePhone;
                            }
                            if (itemText.Text == "收货人-邮编")
                            {
                                itemText.Text = singleOrder.ZipCode;
                            }
                            if (itemText.Text == "订单-订单号")
                            {
                                itemText.Text = singleOrder.OrderNum;
                            }
                            if (itemText.Text == "订单-总金额")
                            {
                                itemText.Text = singleOrder.OrderTotalAmount.ToString();
                            }
                            if (itemText.Text == "订单-物品数量")
                            {
                                itemText.Text = singleOrder.OrderProductsNum.ToString();
                            }
                            if (itemText.Text == "订单-备注")
                            {
                                itemText.Text = singleOrder.Text;
                            }
                            if (itemText.Text == "网店名称")
                            {
                                itemText.Text = singleOrder.WebShopName;
                            }
                            if (itemText.Text == "对号-√")
                            {
                                itemText.Text = "√";
                            }

                            #endregion

                        }
                    }
                }

                // 发货人信息等
                get.GetPostAddressByIdAsync(PostAddressID);
                get.GetPostAddressByIdCompleted += new EventHandler<GetPostAddressByIdCompletedEventArgs>(GetPostAddressByIdCompleted);
            }
        }

         /// <summary>
        /// 发货人信息等
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetPostAddressByIdCompleted(object sender, GetPostAddressByIdCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                CNVP_PostAddress singlePostAddress = e.Result;
                TextBlock itemText = null;
                UIElementCollection uiec = MainMap.Children;
                if (uiec.Count > 0)
                {
                    foreach (UIElement ui in uiec)
                    {
                        if (ui.GetType().ToString() == "System.Windows.Controls.TextBlock")
                        {
                            itemText = (TextBlock)ui;
                            #region 发货人信息等
                            if (itemText.Text == "发货人-姓名")
                            {
                                itemText.Text = singlePostAddress.PostTrueName;
                            }
                            if (itemText.Text == "发货人-地区1级")
                            {
                                itemText.Text = singlePostAddress.Province;
                            }
                            if (itemText.Text == "发货人-地区2级")
                            {
                                itemText.Text = singlePostAddress.City;
                            }
                            if (itemText.Text == "发货人-地区3级")
                            {
                                itemText.Text = singlePostAddress.Area;
                            }
                            if (itemText.Text == "发货人-地址")
                            {
                                itemText.Text = singlePostAddress.PostAddress;
                            }
                            if (itemText.Text == "发货人-地区+详细地址")
                            {
                                itemText.Text = singlePostAddress.Province + singlePostAddress.City + singlePostAddress.Area + singlePostAddress.PostAddress;
                            }
                            if (itemText.Text == "发货人-电话")
                            {
                                itemText.Text = singlePostAddress.Phone;
                            }
                            if (itemText.Text == "发货人-手机")
                            {
                                itemText.Text = singlePostAddress.MobilePhone;
                            }
                            if (itemText.Text == "发货人-邮编")
                            {
                                itemText.Text = singlePostAddress.ZipCode;
                            }
                            if (itemText.Text == "当日日期-年月日")
                            {
                                itemText.Text = DateTime.Now.ToString("yyyy-MM-dd");
                            }
                            #endregion
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 拖动矩形
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetAll_DeliveryTemplateCompleted(object sender, GetAll_DeliveryTemplateCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                foreach (CNVP_DeliveryTemplate temp in e.Result)
                {
                    drag.MainMap = MainMap;
                    drag.TextBlockName = temp.ItemName;
                    drag.CreateRecForCan(true, true, temp.RectangleName, double.Parse(temp.MarginLeft.ToString()), double.Parse(temp.MarginTop.ToString()), double.Parse(temp.RectangleWidth.ToString()), double.Parse(temp.RectangleHight.ToString()), temp.ItemName);
                }
                
            }
        }

        /// <summary>
        /// 获取背景图片的事件，并设置画布的背景
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetColumnByIDCompleted(object sender, GetColumnByIDCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                string[]  retStr = e.Result.ToString().Replace('\\', '/').Split(Convert.ToChar("|"));
                txtDeliveryTemplateName.Text = retStr[0];
                string AbsolutePath = HtmlPage.Document.DocumentUri.AbsoluteUri;
                Uri uri = new Uri(AbsolutePath.ToString().Substring(0, AbsolutePath.ToString().LastIndexOf('/')) + "/" + retStr[1], UriKind.Absolute);
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.UriSource = uri;
                bitmapImage.DownloadProgress += new EventHandler<DownloadProgressEventArgs>(bitmapImage_DownloadProgress);

                ImageBrush imgBrush = new ImageBrush();
                imgBrush.Stretch = Stretch.None;
                imgBrush.AlignmentX = AlignmentX.Left;
                imgBrush.AlignmentY = AlignmentY.Top;
                imgBrush.ImageSource = bitmapImage;
                MainMap.Background = imgBrush;
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
        }

        /// <summary>
        /// 图片加载完成事件，设置画布宽度和高度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bitmapImage_DownloadProgress(object sender, DownloadProgressEventArgs e)
        {
            BitmapImage img = sender as BitmapImage;
            if (e.Progress == 100)
            {
                Dispatcher.BeginInvoke(delegate()
                {
                    MainMap.Height = img.PixelHeight;
                    MainMap.Width = img.PixelWidth;
                });
            }
        }

        //返回包含当前详细时间的字符串，用于避免出现同名的字符串
        public string GetCuTimeDetail()
        {
            string cuTime = "JshopYC" + DateTime.Now.ToString("yyyyMMddHHmmssffff");
            return cuTime;
        }

        private void cbAddItem_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //生成随机Name
            string rectangle = GetCuTimeDetail();
            ComboBox cb = (ComboBox)sender;
            string ItemName = ((ComboBoxItem)cb.SelectedItem).Content.ToString();
            drag.MainMap = MainMap;
            drag.TextBlockName = ItemName;
            if (ItemName != "添加")
            {
                drag.CreateRecForCan(true, true, rectangle, 150, 200, 150, 20, ItemName);
            }
        }

        private void btDetele_Click(object sender, RoutedEventArgs e)
        {
            if (!drag.DelAreaCompleted())
            {
                MessageBox.Show("请选择删除文件！");
            }
        }

        private void Array_DeliveryTemplateCompleted(object sender, Array_DeliveryTemplateCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.ToString() == "false")
                {
                    MessageBox.Show("数据操作错误。");
                }
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
        }

        private void btAdd_Click(object sender, RoutedEventArgs e)
        {
            Rectangle item = null;
            TextBlock itemText = null;
            UIElementCollection uiec = MainMap.Children;
            if (uiec.Count > 0)
            {
                string Str_RectangleName = "";
                string Str_ItemName = "";
                string Str_MarginTop = "";
                string Str_MarginLeft = "";
                string Str_RectangleWidth = "";
                string Str_RectangleHight = "";
                foreach (UIElement ui in uiec)
                {
                    if (ui.GetType().ToString() == "System.Windows.Controls.TextBlock")
                    {
                        itemText = (TextBlock)ui;
                        Str_ItemName += itemText.Text + "|";
                    }
                    if (ui.GetType().ToString() == "System.Windows.Shapes.Rectangle")
                    {
                        item = (Rectangle)ui;
                        Str_RectangleName += item.Name + "|";
                       //
                        Str_MarginTop += Canvas.GetTop(item).ToString() + "|";
                        Str_MarginLeft += Canvas.GetLeft(item).ToString() + "|";
                        Str_RectangleWidth += item.Width.ToString() + "|";
                        Str_RectangleHight += item.Height.ToString() + "|";
                    }
                }
                Str_RectangleName = Str_RectangleName.Substring(0, Str_RectangleName.Length - 1);
                Str_ItemName = Str_ItemName.Substring(0, Str_ItemName.Length - 1);
                Str_MarginTop = Str_MarginTop.Substring(0, Str_MarginTop.Length - 1);
                Str_MarginLeft = Str_MarginLeft.Substring(0, Str_MarginLeft.Length - 1);
                Str_RectangleWidth = Str_RectangleWidth.Substring(0, Str_RectangleWidth.Length - 1);
                Str_RectangleHight = Str_RectangleHight.Substring(0, Str_RectangleHight.Length - 1);

                get.Array_DeliveryTemplateAsync(DeliveryWay, Str_RectangleName, Str_ItemName, Str_MarginTop, Str_MarginLeft, Str_RectangleWidth, Str_RectangleHight);
                get.Array_DeliveryTemplateCompleted += new EventHandler<Array_DeliveryTemplateCompletedEventArgs>(Array_DeliveryTemplateCompleted);
                MessageBox.Show("操作成功！");
            }
            else
            {
                MessageBox.Show("请添加信息！");
            }
            
        }

        void btPrint_Click(object sender, RoutedEventArgs e)
        {
            PrintDocument printDoc = new PrintDocument();
            printDoc.BeginPrint += new EventHandler<BeginPrintEventArgs>(OnBeginPrint);
            printDoc.PrintPage += new EventHandler<PrintPageEventArgs>(OnPrintPage);
            printDoc.EndPrint += new EventHandler<EndPrintEventArgs>(OnEndPrint);
            printDoc.Print("Print OrderID" + OrderID + "");
        }
        public Brush Bg { set; get; }
        private void OnBeginPrint(object sender, BeginPrintEventArgs e)
        {
            Bg = MainMap.Background;
            MainMap.Background = null;
        }
        private void OnEndPrint(object sender, EndPrintEventArgs e)
        {
            MainMap.Background = Bg;
        }
        void OnPrintPage(object sender, PrintPageEventArgs args)
        {
            args.PageVisual = MainMap;
        }
    }
}
